package com.rybbaby.tss.platform.websocket.handshake;

import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.platform.consts.PlatformCommonConsts;
import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 谢进伟
 * @description 客戶端与服务器端进行Socket建立连接（握手）和断开
 * @createDate 2017-02-13 下午12:12:52
 */
public class MsgHandShake implements HandshakeInterceptor {

    private Logger log = Logger.getLogger(MsgHandShake.class);

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        HttpSession session = servletRequest.getSession(false);
        Object sessionLoginAdminUserId = session.getId() + "-" + session.getAttribute(PlatformCommonConsts.SESSION_LOGINUSER_OBJ_ID);
        log.info("Websocket:用户[ID:" + sessionLoginAdminUserId + "]已经建立连接");
        if (request instanceof ServletServerHttpRequest) {
            // 标记用户
            if (StringUtils.isNotBlank(sessionLoginAdminUserId)) {
                attributes.put("uid", sessionLoginAdminUserId);
            } else {
                return false;
            }
        }
        return true;
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }

}
